//
//  HYFileImportViewController.m
//  XPlayer
//
//  Created by liguoqing on 2023/9/16.
//

#import "HYFileImportViewController.h"
#import "HYPCImportViewModel.h"
#import "HYHomeMainView.h"
#import <HYUIKit/HYWKWebViewController.h>
#import "HYVideoViewModel.h"
#import "HYAudioRoomViewController.h"
#import "HYVideoRoomViewController.h"
#import "HYPCImportViewController.h"
#import "HYCreatFileAlertView.h"
#import "HYSuspendButton.h"
#import "HYFolderMoveViewController.h"
#import "HYPreviewImageController.h"
#import <SSZipArchive/SSZipArchive.h>
#import "HYFaceToFaceController.h"
#import "XDSReaderHeader.h"

@interface HYFileImportViewController ()

@property (nonatomic, strong) HYPCImportViewModel *viewModel;

@property (nonatomic, strong) HYHomeMainView *mainView;

@property (nonatomic, strong) HYHomeMainView *videoView;

@property (nonatomic, strong) HYHomeMainView *audioView;

@property (nonatomic, strong) HYHomeMainView *fileView;

@property (nonatomic, strong) HYHomeMainView *picView;

@property (nonatomic, strong) HYHomeMainView *otherView;

@property (nonatomic, strong) HYSuspendButton *createBtn;

@property (nonatomic, strong) UITextField *textField;

@property (nonatomic, strong) UITextField *zipPasswordField;

@end

@implementation HYFileImportViewController

- (void)dealloc
{
    CLog(@"dealloc -- %@",[self class]);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = self.folderName;
    [self configUI];
    [self bindSignal];
    [self loadData];
    if (self.isSelectFile) {
        [self.navigationBarView.leftButton setImage:[UIImage imageNamed:@"nav_btn_close_n"] forState:UIControlStateNormal];
    }
}
- (void)leftButtonClick
{
    if (self.isSelectFile) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.viewModel.isSelectFile = self.isSelectFile;
    [self.viewModel startMonitorFile];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.viewModel stopMonitorFile];
}

- (void)configUI
{
    CGFloat hToolViewY = NAVIGATIONBAR_HEIGHT+2.5;
    CGFloat hToolHeight = [self preferredCategoryViewHeight];
    CGFloat tContainerHeight = kMainScreenHeight-hToolViewY-HOME_BAR_HEIGHT;
    CGFloat tContainerY = hToolViewY+hToolHeight;
    self.titles = @[NSLocalizedString(@"全部", nil),NSLocalizedString(@"视频", nil),NSLocalizedString(@"音频", nil),NSLocalizedString(@"文件", nil),NSLocalizedString(@"图片", nil),NSLocalizedString(@"其他", nil)];
    self.myCategoryView.titles = self.titles;
    self.myCategoryView.frame = CGRectMake(0, hToolViewY, kScreenWidth, hToolHeight);
    self.listContainerView.frame = CGRectMake(0, tContainerY, kScreenWidth, tContainerHeight);
    [self.view addSubview:self.myCategoryView];
    [self.view addSubview:self.listContainerView];
    if (!_isSelectFile) {
        [self addCreateBtn];
    }
}

- (void)addCreateBtn
{
    [self.view addSubview:self.createBtn];
    [self.createBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-TABLE_BAR_HEIGHT-15);
        make.right.mas_equalTo(-15);
        make.width.height.mas_equalTo(60);
    }];
    [self.createBtn setImage:[UIImage imageNamed:@"icon_btn_add"]];
}

- (void)bindSignal
{
    @weakify(self);
    [self.viewModel.showFileSubject subscribeNext:^(HYHomeFileItemViewModel *itemVm) {
        @strongify(self);
        switch (itemVm.fileType) {
            case HYHomeFileType_Folder:
                {
                    [self showSubFolder:itemVm.filePath folderName:itemVm.fileName];
                }
                break;
            case HYHomeFileType_File:
                {
                    if (self.isSelectFile) {
                        !self.selectFile ?: self.selectFile(itemVm.filePath,itemVm.fileName,itemVm.fileSuffixName);
                        [self dismissViewControllerAnimated:YES completion:nil];
                        return;
                    }
                    [self showWordFile:itemVm.filePath fileName:itemVm.fileName];
                }
                break;
            case HYHomeFileType_Pic:
                {
                    if (self.isSelectFile) {
                        !self.selectFile ?: self.selectFile(itemVm.filePath,itemVm.fileName,itemVm.fileSuffixName);
                        [self dismissViewControllerAnimated:YES completion:nil];
                        return;
                    }
                    RACTuple *tuple = [self.viewModel showImageWithFileVM:itemVm];
                    NSArray *imageSoure = tuple.first;
                    NSInteger currentIndex = [tuple.second integerValue];
                    [self showImagePath:imageSoure currentImageIndex:currentIndex];
                }
                break;
            case HYHomeFileType_Audio:
                {
                    if (self.isSelectFile) {
                        !self.selectFile ?: self.selectFile(itemVm.filePath,itemVm.fileName,itemVm.fileSuffixName);
                        [self dismissViewControllerAnimated:YES completion:nil];
                        return;
                    }
                    [self showAudioWithItemVM:itemVm];
                }
                break;
            case HYHomeFileType_Video:
                {
                    if (self.isSelectFile) {
                        !self.selectFile ?: self.selectFile(itemVm.filePath,itemVm.fileName,itemVm.fileSuffixName);
                        [self dismissViewControllerAnimated:YES completion:nil];
                        return;
                    }
                    [self showVideoWithItemVM:itemVm];
                }
                break;
            case HYHomeFileType_Zip:
                {
                    [HYHub showMessage:NSLocalizedString(@"文件解压后才能查看",nil)];
                }
                break;
            case HYHomeFileType_Other:
                {
                    [HYHub showMessage:NSLocalizedString(@"该文件暂不支持预览，技术小哥正在加快研发中", nil)];
                }
                break;
                
            default:
                break;
        }
    }];
    [self.viewModel.setSubject subscribeNext:^(HYHomeFileItemViewModel *itemVM) {
        @strongify(self);
        if (self.isSelectFile) {
            return;
        }
        [self setfolder:itemVM];
    }];
    [self.viewModel.refreshSubject subscribeNext:^(id x) {
        @strongify(self);
        if(self.refreshBlock){
            self.refreshBlock();
        }
    }];
}

- (void)loadData
{
    [self.viewModel fetchData];
}

#pragma mark - 新建资源
- (void)createBtnAction
{
    HYCreatFileAlertView *alertView = [[HYCreatFileAlertView alloc]initWithItemTypes:@[@(HYCreatFileType_Folder),@(HYCreatFileType_Import),@(HYCreatFileType_FaceToFace)] clickBlock:^(HYCreatFileType type) {
        switch (type) {
            case HYCreatFileType_Folder:
                {
                    [self newCreateFolder:YES fileViewModel:nil];
                }
                break;
            case HYCreatFileType_Import:
                {
                    [self jumpFileImport];
                }
                break;
            case HYCreatFileType_FaceToFace:
                {
                    [self faceToFaceFileTransfer];
                }
                break;
            default:
                break;
        }
    }];
    [alertView show];
}

#pragma mark - 新建文件夹
- (void)newCreateFolder:(BOOL)isNewCreate fileViewModel:(HYHomeFileItemViewModel *)fileVM
{
    @weakify(self);
    NSString *title = isNewCreate?NSLocalizedString(@"新建文件夹", nil):NSLocalizedString(@"重命名", nil);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        @strongify(self);
        if(!isNewCreate){
            textField.text = [CommUtls fetchVideoNameWithFullName:fileVM.fileName];
        }
        self.textField = textField;
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        if(self.textField.text.length){
            if(isNewCreate){// 新建文件夹
                [self.viewModel createFolderWithFolderName:self.textField.text completeBlock:nil];
            }else{// 修改文件名称
                if(![fileVM.fileName isEqualToString:self.textField.text]){
                    if(fileVM.fileSuffixName.length){
                        fileVM.fileName = [self.textField.text stringByAppendingFormat:@".%@",fileVM.fileSuffixName];
                    }else{
                        fileVM.fileName = self.textField.text;
                    }
                    [self.viewModel modifyFileNameWithFileViewModel:fileVM];
                }
            }
        }
        self.textField = nil;
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        self.textField = nil;
    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 文件导入
- (void)jumpFileImport
{
    HYPCImportViewController *pcVC = [[HYPCImportViewController alloc]init];
    @weakify(self);
    [pcVC fileChangeRefreshBlock:^{
        @strongify(self);
        [self loadData];
    }];
    [self.navigationController pushViewController:pcVC animated:YES];
}

#pragma mark - 跳转子文件夹
- (void)showSubFolder:(NSString *)filePath folderName:(NSString *)folderName
{
    @weakify(self);
    HYFileImportViewController *subVC = [[HYFileImportViewController alloc]initWithParentPath:self.folderPath
                                                                            currentfolderPath:filePath
                                                                            currentfolderName:folderName];
    subVC.isSelectFile = self.isSelectFile;
    [subVC fileChangeRefreshBlock:^{
        @strongify(self);
        [self loadData];
    }];
    if (self.isSelectFile) {
        subVC.selectFile = ^(NSString *filePath, NSString *fileName, NSString *fileSuffixName) {
            @strongify(self);
            !self.selectFile ?: self.selectFile(filePath,fileName,fileSuffixName);
        };
        subVC.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:subVC animated:YES completion:nil];
    }
    [self.navigationController pushViewController:subVC animated:YES];
}

#pragma mark - 查看文本
- (void)showWordFile:(NSString *)filePath fileName:(NSString *)fileName
{
    NSString *fileType = [filePath.lastPathComponent pathExtension].lowercaseString;
    if([@[@"epub",@"txt"] containsObject:fileType]){
        [[XDSReadManager sharedManager] updateReadRect];
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        [HYHub loadMessage:NSLocalizedString(@"正在加载中,请耐心等待", nil)];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            XDSBookModel *bookModel = [XDSBookModel getLocalModelWithURL:fileURL];
            dispatch_async(dispatch_get_main_queue(), ^{
                [HYHub dismiss];
                XDSReadPageViewController *pageView = [[XDSReadPageViewController alloc] init];
                [[XDSReadManager sharedManager] setResourceURL:fileURL];//文件位置
                [[XDSReadManager sharedManager] setBookModel:bookModel];
                [[XDSReadManager sharedManager] setRmDelegate:pageView];
                self.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:pageView animated:YES];
            });
        });
    }else{
        HYWKWebViewController *webVC = [[HYWKWebViewController alloc]init];
        webVC.localUrl = filePath;
        webVC.staticNavTitle = fileName;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}
- (void)showImagePath:(NSArray *)imagePaths currentImageIndex:(NSInteger)currentIndex
{
    HYPreviewImageController *showImgVC = [[HYPreviewImageController alloc]initWithImages:imagePaths currentIndex:currentIndex];
    showImgVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:showImgVC animated:YES completion:nil];
}

#pragma mark - 查看音频
- (void)showAudioWithItemVM:(HYHomeFileItemViewModel *)itemVm
{
    HYVideoViewModel *viewModel = [self.viewModel fetchPlayVideoConfigWithItemViewModel:itemVm];
    HYAudioRoomViewController *audioRoomVC = [[HYAudioRoomViewController alloc]initWithViewModel:viewModel];
    [self.navigationController pushViewController:audioRoomVC animated:YES];
}

#pragma mark - 查看视频
- (void)showVideoWithItemVM:(HYHomeFileItemViewModel *)itemVm
{
    HYVideoViewModel *viewModel = [self.viewModel fetchPlayVideoConfigWithItemViewModel:itemVm];
    HYVideoRoomViewController *videoRoomVC = [[HYVideoRoomViewController alloc]initWithViewModel:viewModel];
    [self.navigationController pushViewController:videoRoomVC animated:YES];
}
//校验 是否存在密码 有密码输入密码 看能不能打开 能打开直接压缩
- (void)verifyUnzipFile:(HYHomeFileItemViewModel *)itemVm
{
    BOOL isPassword = [SSZipArchive isFilePasswordProtectedAtPath:itemVm.filePath];
    if (isPassword) {
        [self showUrlAlert:itemVm.filePath];
        return;
    }
    [self unzipFile:itemVm.filePath withPassword:nil];
}
- (BOOL)canOpenFile:(NSString *)path withPassword:(NSString *)password
{
    BOOL canOpenPasswordZipFile = [SSZipArchive isPasswordValidForArchiveAtPath:path password:password error:nil];
    return canOpenPasswordZipFile;
}
- (void)unzipFile:(NSString *)path withPassword:(NSString *)password
{
    NSString *destinationPath = [path stringByDeletingLastPathComponent];
    [SSZipArchive unzipFileAtPath:path toDestination:destinationPath preserveAttributes:YES overwrite:YES nestedZipLevel:0 password:password error:nil delegate:nil progressHandler:nil completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            [HYHub showMessage:NSLocalizedString(@"解压成功", nil)];
            [self.viewModel fetchData];
        }else{
            [HYHub showMessage:NSLocalizedString(@"解压失败,请检查文件是否完整", nil)];
        }
    }];
}
- (void)showUrlAlert:(NSString *)path
{
    @weakify(self);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"请输入密码", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        @strongify(self);
        self.zipPasswordField = textField;
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        if (!self.zipPasswordField.text.length) {
            [HYHub showMessage:NSLocalizedString(@"请输入密码", nil)];
            return;
        }
        if ([self canOpenFile:path withPassword:self.zipPasswordField.text]) {
            [self unzipFile:path withPassword:self.zipPasswordField.text];
        }else{
            [HYHub showMessage:NSLocalizedString(@"密码错误", nil)];
        }
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        self.zipPasswordField = nil;
    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 文件设置
- (void)setfolder:(HYHomeFileItemViewModel *)folderVM
{
    NSArray *itemsTypes = @[@(HYCreatFileType_Rename),@(HYCreatFileType_Delete),@(HYCreatFileType_Move)];
    if(folderVM.fileType == HYHomeFileType_Zip){
        itemsTypes = @[@(HYCreatFileType_Rename),@(HYCreatFileType_Delete),@(HYCreatFileType_Move),@(HYCreatFileType_unZip)];
    }
    @weakify(self);
    HYCreatFileAlertView *alertView = [[HYCreatFileAlertView alloc]initWithItemTypes:itemsTypes clickBlock:^(HYCreatFileType type) {
        @strongify(self);
        switch (type) {
            case HYCreatFileType_Rename:
                {
                    [self newCreateFolder:NO fileViewModel:folderVM];
                }
                break;
            case HYCreatFileType_Delete:
                {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"温馨提示", nil) message:NSLocalizedString(@"删除后无法恢复，请谨慎操作！", nil) preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        @strongify(self);
                        [self.viewModel deleteFilWithFileViewModel:folderVM];
                    }];
                    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:nil];
                    [alert addAction:sureAction];
                    [alert addAction:cancleAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }
                break;
            case HYCreatFileType_Move:
                {
                    NSArray *folderSource = [self.viewModel fetchCurrentListFolder:folderVM];
                    [self moveFolder:folderVM folderSource:folderSource];
                }
                break;
            case HYCreatFileType_unZip:
                {
                    [self verifyUnzipFile:folderVM];
                }
                break;
            default:
                break;
        }
    }];
    [alertView show];
}

#pragma mark - 移动文件夹
- (void)moveFolder:(HYHomeFileItemViewModel *)fileViewModel folderSource:(NSArray *)folderSource
{
    HYFolderMoveViewController *folderVC = [[HYFolderMoveViewController alloc]initWithFolderSource:folderSource folderPath:self.folderPath];
    folderVC.fileViewModel = fileViewModel;
    folderVC.viewModel = self.viewModel;
    folderVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:folderVC animated:YES completion:nil];
}

#pragma mark - 面对面传送
- (void)faceToFaceFileTransfer
{
    HYFaceToFaceController *vc = [[HYFaceToFaceController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - JXCategoryListContentViewDelegate
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index
{
    HYHomeMainView *mainView;
    if(index == 0){
        mainView = [[HYHomeMainView alloc]initWithViewModel:self.viewModel fileType:HYHomeFileType_All];
        self.mainView = mainView;
    }else if (index == 1){
        mainView = [[HYHomeMainView alloc]initWithViewModel:self.viewModel fileType:HYHomeFileType_Video];
        self.videoView = mainView;
    }else if (index == 2){
        mainView = [[HYHomeMainView alloc]initWithViewModel:self.viewModel fileType:HYHomeFileType_Audio];
        self.audioView = mainView;
    }else if (index == 3){
        mainView = [[HYHomeMainView alloc]initWithViewModel:self.viewModel fileType:HYHomeFileType_File];
        self.audioView = mainView;
    }else if (index == 4){
        mainView = [[HYHomeMainView alloc]initWithViewModel:self.viewModel fileType:HYHomeFileType_Pic];
        self.audioView = mainView;
    }else if (index == 5){
        mainView = [[HYHomeMainView alloc]initWithViewModel:self.viewModel fileType:HYHomeFileType_Other];
        self.audioView = mainView;
    }
    return mainView;
}

#pragma mark - loadLazy
- (HYPCImportViewModel *)viewModel
{
    if(!_viewModel){
        _viewModel = [[HYPCImportViewModel alloc]initWithParentPath:self.parentPath currentFolderPath:self.folderPath];
    }
    return _viewModel;
}

- (UIView *)createBtn
{
    if(!_createBtn){
        @weakify(self);
        _createBtn = [[HYSuspendButton alloc]initWithClickBlock:^{
            @strongify(self);
            [self createBtnAction];
        }margin:kLeftMargin_15];
        _createBtn.layer.cornerRadius = 30;
        _createBtn.layer.masksToBounds = YES;
    }
    return _createBtn;
}

@end
